package com.gitee.huxing.algorithmic.daily;

import com.gitee.huxing.algorithmic.TreeNode;

/**
 * @Description: 二叉树平衡
 * @ProjectName: AlgorithmicPactice
 * @Package: com.gitee.huxing.algorithmic.daily
 * @ClassName: TreeBalance
 * @Author: huxing
 * @DateTime: 2022-03-09 10:12 AM
 */
public class TreeBalance {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(isBalanced(root));
    }

    public static boolean isBalanced(TreeNode root) {
        return height(root) >= 0;
    }
    public static int height(TreeNode root){
        if (root == null){
            return 0;
        }
        int val = root.val;
        int leftVal = root.left == null ? -1 : root.left.val;
        int rightVal = root.right == null ? -1 : root.right.val;
        System.out.println(val + " " + leftVal + " " + rightVal);
        int leftHeight = height(root.left);
        int rightHeight = height(root.right);
        if (leftHeight == -1 || rightHeight == -1
                || Math.abs(leftHeight - rightHeight) > 1){
            System.out.println("return: " + -1);
            return -1;
        } else{
            System.out.println("return: " + (Math.max(leftHeight, rightHeight) + 1));
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }
}
